<template>
    <div class="rx-app-design-home " ref="container" style="width:100%;height: 100%">
        <a-layout class="rx-app-design-home-layout" style="min-height: 100vh" theme="light">
            <a-layout-header class="rx-app-design-header" >
                <div class="rx-app-left-content">
                <span class="rx-app-icon">
                    <rx-use-icon v-model="aIcon"></rx-use-icon>
                </span>
                    <span class="rx-app-text">{{appName}}</span>
                </div>
                <div class="rx-app-header-menu">
                    <div class="rx-app-menu-roll">
                        <rx-app-menu v-model="menuKey" :menus="headMenu" :menuClick="menuClick"/>
                    </div>
                </div>
                <div class="rx-app-preview" @click="backToAdmin()" v-if="showBack">
                    <a-icon type="rollback" />
                    {{i18n('return','返回')}}
                </div>
                <div class="rx-app-preview" @click="appPreview(currentApp)">
                    <my-icon type="iconmanage"/>
                    {{i18n('AppPreview','应用预览')}}
                </div>
            </a-layout-header>
            <a-layout theme="light">
                <a-layout-sider v-model="collapsed" collapsible v-if="menuShow" collapsedWidth="60">
                    <template slot="trigger">
                        <a-icon type="menu-unfold" v-if="collapsed"/>
                        <a-icon type="menu-fold" v-else/>
                    </template>
                    <div class="rx-menu-roll">
                        <rx-app-menu
                            v-model="leftMenuKey"
                            :openKeys.sync="openKeys"
                            :menus="leftMenus"
                            :mode="'inline'"
                            :menuClick="leftMenuClick"
                        />
                    </div>
                </a-layout-sider>

                <a-layout-content>
                    <div class="rx-app-design-content">
                        <div class="rx-app-design-nav" v-if="!menuKey.includes('appNav')">
                            <appNavToolbar v-model="navKey" :navs="navs" @tabDelChange="tabDelChange" :tabClick="tabClick"></appNavToolbar>
                        </div>
                        <div class="rx-app-design-container">
                            <div class="rx-app-design-container-roll">
                            <router-view  :currentApp="currentApp"/>
                            </div>
                        </div>
                    </div>
                </a-layout-content>
            </a-layout>
        </a-layout>
    </div>
</template>

<script>
import rxAppMenu from './rx-app-menu'
import appNavToolbar from './app-nav-toolbar'
import {headMenu,leftMenus} from './appMenus.js'
import {RxUseIcon} from "@lowcode/jpaas-common-lib"
import waterMark from "@/assets/js/initWaterMark";
import SysAppApi from "@/api/system/core/sysApp";
import appPreview from "@/layouts/AppDesignPage/appPreview";

let adminOpenedChannel = new BroadcastChannel("adminOpened");
export default {
    name: "AppDesignHome",
    mixins: [waterMark,appPreview],
    components:{
        rxAppMenu,appNavToolbar,RxUseIcon
    },
    computed:{

        leftMenus(){
            let key = this.menuKey[0];
            return this.leftMenuObj[key]
        },
        aIcon(){
            return this.appIcon;
        },
        menuShow(){
            if(this.menuKey !='appNav' && this.leftMenus && this.leftMenus.length > 1){
                return true ;
            }
            return false ;
        },
    },
    data(){
        return {
            appIcon:'',
            appName:'',
            headMenu,
            leftMenuObj:leftMenus,
            collapsed:false,
            menuKey:[],//头部菜单选中key
            leftMenuKey:[],//左侧菜单选中key
            openKeys:[],//左侧菜单展开项
            navKey:'',//导航条选中key
            navs:[],//导航条数据
            routeChange:false,
            keyChange:false,
            showBack:false,
            currentApp:{},//当前应用的数据
        }
    },
    created(){
        this.initAppDesign()
        let self_=this;
        //当其他的主页面关掉的时候发送消息过来，这里就显示返回按钮。
        adminOpenedChannel.onmessage=function (event){
            self_.showBack = (event.data=='close');
        }
    },
    mounted(){
        this.$bus.on('changeRouter',(name)=>{
            this.setInitAppData(name);
        })
        console.log(this.headMenu)

    },
    methods:{
        i18n(name, text, key) {
            return this.$ti18(name, text, "appHome", key);
        },
        tabDelChange(key,navs){
            this.navs = navs ;
            this.setInitAppData(key)
        },
        setInitAppData(name){
            if(!name){
                this.menuKey = ['appNav'];
                this.leftMenuKey = [] ;
                this.openKeys = []
                this.navKey = ''
             //   this.navs = []
                return ;
            }
            let selectMenu =  this.getMenuKey(name);
            this.menuKey = [selectMenu['headMenuKey']];
            this.setNavs(selectMenu)
            this.leftMenuKey = [selectMenu.key]
            let parents = this.getParentNode(this.leftMenuObj[selectMenu.headMenuKey],selectMenu.key,'key');
            //设置展开的菜单key
            this.setOpenKeys(parents,selectMenu.key);
        },
        initAppDesign(){
            let {name,query:{appId,appIcon,appName}}  = this.$route ;
            if(!appId){
                this.$message.warning('当前应用没有appId,请确保入口正确~')
            }
            SysAppApi.get(appId).then(res=>{
                this.currentApp=res.data;
            })
            this.appName = appName ?appName : '应用开发' ;
            document.title = appName ;
            this.appIcon = appIcon ?appIcon : "{type:'jpaasIcon',icon:'iconmanage'}" ;
            if(name === 'appHome'){
                this.menuKey = ['appNav']
            }else {
                this.setInitAppData(name);
            }
        },
        setAppData(){
            let {query:{appId,appIcon,appName}}  = this.$route ;
            if(!appId){
                this.$message.warning('当前应用没有appId,请确保入口正确~')
            }
            this.appName = appName ?appName : '应用开发' ;
            this.appIcon = appIcon ?appIcon : "{type:'jpaasIcon',icon:'iconmanage'}" ;
        },
        getMenuKey(selectKey){
            let { leftMenuObj } = this ;
            let select = {}
            let getMenu = (menu,key) => {
                for (let item of menu){
                    if(Object.keys(select).length > 0){
                        return  select
                    }
                    if(item.key === key){
                        select = item
                    }else if(item.children && item.children.length > 0){
                          getMenu(item.children,key)
                    }
                }
            }
            for (let key in leftMenuObj){
                if(leftMenuObj[key]){
                    if(Object.keys(select).length > 0){
                        return  select
                    }
                    getMenu(leftMenuObj[key],selectKey);
                }
            }
            return select ;
        },
        getParentNode(obj, id,field){
            //获取当前id的 所有祖先元素
            let getParent = (list, id,field) => {
                for (let item of list) {
                    if (item[field] == id) {
                        return [item]
                    }
                    if (item.children) {
                        let node = getParent(item.children, id,field);
                        if (node !== undefined) {
                            return node.concat(item)
                        }
                    }
                }
            }
            return getParent(obj, id,field)
        },

        setOpenKeys(parents,key){
            let parentData = parents.filter(item=>item.key != key);
            if(parentData.length === 0 ){ return }
            //设置展开的key
            for (let item of parentData){
                if(item.key != key){
                    let hasKey = this.openKeys.find(menuKey =>menuKey === item.key);
                    if(!hasKey){
                        this.openKeys.push(item.key);
                    }
                }
            }
        },
        setNavs(selectMenu){
            this.navKey = selectMenu.key ;
            let hasNav = this.navs.find(nav=>nav.key === selectMenu.key);
            if(!hasNav){
                this.navs.push(selectMenu);
            }
        },
        leftMenuClick(menu){
            this.setInitAppData(menu.key)
        },
        setMenuData(selectMenu){
            let _key = this.menuKey[0]
            let menus = this.leftMenuObj[_key];
            let parents = this.getParentNode(menus,selectMenu.key,'key');
            //设置展开的菜单key
            this.setOpenKeys(parents,selectMenu.key);
            //设置选中的菜单key
            this.leftMenuKey = [selectMenu.key]
            //设置导航条
            this.setNavs(selectMenu)
        },
        /**
         * 处理跳转路由。
         * @param menu
         * @returns {boolean}
         */
        handRouterPath(menu){
            if(menu.type && menu.type=="routerPath"){
                let { query } = this.$route
                this.$router.push({
                    path:'/appDesign/appHome',
                    query
                })
                return true;
            }
            return false;
        },
        /**
         * 跳转到新的链接
         * @param menu
         * @returns {boolean}
         */
        handLink(menu){
            if(!menu.type || menu.type!=="link" ){
                return false;
            }

            let { query } = this.$route
            let url=menu.path;
            if(query.appId){
                let params="appId=" +query.appId;
                url+=(url.indexOf("?")!=-1)?"&":"?";
                url+=params;
            }
            window.open(url);
            return true;

        },
        menuClick(menu){
            let handled=this.handRouterPath(menu);
            if(handled){
                return;
            }
            handled=this.handLink(menu);
            if(handled){
                return;
            }

            this.menuKey = [menu.key];

            let menus = this.leftMenuObj[menu.key];
            if(!menus){
                return;
            }
            let selectMenu = this.getFirstMenu(menus);
            if(selectMenu){
               this.setMenuData(selectMenu)
            }
        },
        getLeftMenuKey(menu){
            let getKey = (menuData)=>{
                for (let item of menuData){
                    if(item.key ){

                    }
                    if(item.children && item.children.length > 0){
                        return getKey(item.children);
                    }
                }
            }
            return getKey(menu)
        },
        tabClick(menu){
            this.menuKey = [menu.headMenuKey]
            this.leftMenuKey = [menu.key]
            let parents = this.getParentNode(this.leftMenus,menu.key,'key');
            //设置展开的菜单key
            this.setOpenKeys(parents,menu.key);
        },
        printPath(){
            /*
            * 打印当前路由的页面地址
            * */
            let { $route } = this ;
            if($route.matched.length>0){
                $route.matched.forEach(item=>{
                    console.dir(item.components.default['__file'])
                })
            }
        }
    },
    watch:{
        leftMenuKey:{
            handler(v){
                if(this.routeChange){//通过回退路由触发的 不走这里；
                    this.routeChange = false ;
                    return ;
                }
                this.keyChange = true ;
                let { appId,appName,appIcon } = this.$route.query ;
                this.appName = appName ?appName : '应用开发' ;
                this.appIcon = appIcon ?appIcon : "{type:'jpaasIcon',icon:'iconmanage'}" ;
                this.printPath()
                this.$router.push({
                    name: v[0] ?v[0] : 'appHome',
                    query:{ appId,appName,appIcon }
                });
            },
            deep:true
        },
        $route:{
            handler(v){
                if(v.name !== 'screen'){//点击浏览器后退触发;
                    //如果是通过leftMenuKey改变触发的 那就不走这里;
                    if(this.keyChange){
                        this.keyChange = false ;
                        return ;
                    }
                    this.routeChange = true ;
                    this.setInitAppData(v.name === 'appHome'?'':v.name)
                }
            },
            deep:true
        }
    }
}
</script>

<style scoped>
.navbar {
    margin-top: 20px;
    width: 756px;
    padding-right: 20px;
    height: 688px;
    overflow: hidden;
}

.navbar img {
    width: 736px;
    height: 688px;
}
.rx-app-header-menu >>> .rx-app-menu-box{
    color: #fff;
}
.rx-app-design-home-layout,
.rx-app-design-home{
    height: 100%;
    width: 100%;
}
.rx-app-icon{
    display: inline-block;
    text-align: center;
    line-height: 34px;
    height: 34px;
    width: 34px;
    border-radius: 8px;
    background: #fff;
    margin: 0 10px;
    color: #4285f4;
    font-size: 20px;
    vertical-align: middle;
}
.rx-app-text{
    display: inline-block;
    vertical-align: middle;
}
.rx-app-design-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
    height: 50px;
    line-height: normal;
    background: #4285f4;
    color: #fff;
}
.rx-app-left-content{
    margin-right: 30px;
}

.rx-app-header-menu{
    flex: 1;
    height: 50px;
    background: #4285f4;
    position: relative;
}
.rx-app-menu-roll{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
.rx-app-header-menu >>> .ant-menu{
    background:#4285f4 ;
}
.rx-app-header-menu >>> .ant-menu-horizontal,
.rx-app-header-menu >>> .ant-menu-submenu-title{
    height: 50px;
    line-height: 50px;
    border-bottom: none;
}
.rx-app-preview{
    padding:6px 15px;
    border-radius: 16px;
    background:rgba(255,255,255,.3);
    margin-left: 20px;
    margin-right: 10px;
    color: #fff;
    cursor:pointer;
}

.rx-app-design-content{
    display: flex;
    flex-direction: column;
    background: #f3f3f3;
    height: 100%;
}

.rx-app-design-center > h4{
    font-size: 16px;
    font-weight: bold;
    padding: 26px 0 13px;
    margin: 0;

}

.rx-app-design-home >>> .ant-layout-content{
    border-left: 1px solid #e8e8e8;
}
.rx-app-design-nav{
    height: 40px;
    background: #fff;
}
.rx-app-design-container{
    padding: 10px;
    flex: 1;
    position: relative;
}
.rx-app-design-container-roll{
    background: #fff;
    border-radius: 4px;
    position: absolute;
    inset: 10px;
    overflow: auto;
    box-sizing: border-box;
}

.rx-app-design-content::-webkit-scrollbar-thumb{
    display: none;
}
.rx-app-design-content:hover::-webkit-scrollbar-thumb{
    display: block;
}
.rx-app-design-home-layout >>> .ant-layout-content{
    position: relative;
}
.rx-menu-roll{
    height: 100%;
    width: 100%;
    overflow: hidden;
}
.rx-menu-roll:hover{
    overflow: auto;
}
.rx-app-design-home >>> .ant-layout-sider-trigger,
.rx-app-design-home >>> .ant-layout-sider{
    background: #fff;
}
.rx-app-design-home >>> .ant-layout-sider-trigger{
    color: black;
}

</style>